//
//  PictureSelectorViewController.swift
//  SinaWeibo
//
//  Created by yang on 15/11/19.
//  Copyright © 2015年 yang. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"
private let column :CGFloat = 4
private let pictureCellMaigin: CGFloat = 10
private let maxImageCount = 9
class PictureSelectorViewController: UICollectionViewController {
    lazy var imageList = [UIImage]()
    init(){
    let layout = UICollectionViewFlowLayout()
        let w = (screenW - (column + 1) * pictureCellMaigin) / column
        layout.itemSize = CGSize(width: w, height: w)
        layout.minimumLineSpacing = pictureCellMaigin
        layout.minimumInteritemSpacing = pictureCellMaigin
        layout.sectionInset = UIEdgeInsets(top: pictureCellMaigin, left: pictureCellMaigin, bottom: 0, right: pictureCellMaigin)
        super.init(collectionViewLayout:layout)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.collectionView!.registerClass(PictureSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()

    }
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageList.count + (imageList.count == maxImageCount ? 0 : 1)
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PictureSelectorCell
        cell.delegate = self
        cell.backgroundColor = UIColor.whiteColor()
        if indexPath.item == imageList.count{
            cell.image = nil
        }else{
            cell.image = imageList[indexPath.item]
        }
        return cell
    }

}
//实现代理方法
extension PictureSelectorViewController:PictureSelectorCellDelegate{
    //添加图片
    func userWillAddPicture(cell:PictureSelectorCell){
        //已经有图片就 return
        if cell.image != nil{
           return
        }
        let picker = UIImagePickerController()
        picker.delegate = self
        presentViewController(picker, animated: true, completion: nil)
    }
    //删除图片
    func userWillDeletePicture(cell:PictureSelectorCell){
        let indexPath = collectionView?.indexPathForCell(cell)
        imageList.removeAtIndex(indexPath!.item)
        UIView.animateWithDuration(0.25, animations: { () -> Void in
               cell.alpha = 0
            }) { (_) -> Void in
              
                cell.alpha = 1
               self.collectionView?.reloadData()
        }
    }
}
//遵守图片选择器的代理协议
extension PictureSelectorViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        imageList.append(image)
        collectionView?.reloadData()
        dismissViewControllerAnimated(true, completion: nil)
    }

}
//PictureSelectorCell的代理协议
@objc protocol PictureSelectorCellDelegate:NSObjectProtocol{
    //协议方法
    optional func userWillAddPicture(cell:PictureSelectorCell)
    
    optional func userWillDeletePicture(cell:PictureSelectorCell)
    
}
class PictureSelectorCell:UICollectionViewCell{
    //代理属性
    weak var delegate:PictureSelectorCellDelegate?
    // Button 的点击方法
    @objc func addBtnDidClick(){
      delegate?.userWillAddPicture?(self)
    }
    @objc func deleteBtnDidClick(){
      delegate?.userWillDeletePicture?(self)
    }
    //重写属性传值
    var image:UIImage?{
        didSet{
            deleteBtn.hidden = (image == nil)
            if image != nil {
            addBtn.setImage(image, forState: .Normal)
            }else{
            addBtn.setImage(UIImage(named: "compose_pic_add"), forState: .Normal)
            addBtn.setImage(UIImage(named: "compose_pic_add_Highlighted"), forState: .
                Highlighted)
            }
        }
    }
    override init(frame: CGRect) {
        super.init(frame:frame)
        setupUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //添加子控件
    private func setupUI(){
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.right.top.equalTo(contentView)
        }
        addBtn.addTarget(self, action: "addBtnDidClick", forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: "deleteBtnDidClick", forControlEvents: .TouchUpInside)
    }
    //懒加载子控件
    private lazy var addBtn:UIButton = UIButton(title: nil, backImage:  "compose_pic_add", color: nil)
    private lazy var deleteBtn:UIButton = UIButton(title: nil, backImage:  "compose_photo_close", color: nil)
}